#include "map.h"
#include <QNetworkProxyFactory>
#include <QNetworkReply>
#include <QWebFrame>
#include <QFile>
#include <QMessageBox>
#include <QInputDialog>
#include <QApplication>
#include <QByteArray>
#include <QString>
#include <QPlainTextEdit>
#include <QWebView>
#include <QLineEdit>

Map::Map(QWebView *tmapview, QLineEdit *tmapline, QObject *parent) : QObject(parent), zoomLevel( 10 )
{
    latitude = "4.373095";
    longitude = "51.999547";
    mapview = tmapview;
    mapline = tmapline;
    QNetworkProxyFactory::setUseSystemConfiguration(true);

    QFile file;
    file.setFileName(":/jquery.min.js");
    file.open(QIODevice::ReadOnly);
    jQuery = file.readAll();
    file.close();

    connect(mapview->page()->mainFrame(), SIGNAL(javaScriptWindowObjectCleared()),
            this, SLOT(populateJavaScriptWindowObject()));

    manager = new QNetworkAccessManager(this);
    mapline->setText("Delft");

    connect( manager, SIGNAL( finished (QNetworkReply *) ), this,
                         SLOT (finished(QNetworkReply *) ) );

    mapview->setUrl( QUrl("qrc:/gmaps_files/gmaps.htm") );
}

void Map::changeEvent(QEvent *e)
{
        qDebug("Running");
  emit changeReceived(e);
}

void Map::on_lineEdit_returnPressed()
{
#if defined(BROWSER)
    QString url = mapline->text();

    if ( !url.contains( QRegExp("^[a-z]*://:")))
        url = "http://" + url;

    loadUrl( url );
#else
    on_buttonSearch_pressed();
#endif
}

void Map::loadUrl(const QString url)
{
    mapline->setText( url );
    mapview->setUrl( url );
}

//void Map::on_webView_titleChanged(QString title)
//{
//    setWindowTitle( title );
//}

//void Map::on_webView_iconChanged()
//{
//    setWindowIcon( mapview->icon() );
//}

void Map::on_webView_urlChanged(QUrl url )
{
#if defined(BROWSER)
    mapline->setText( url.toString() );
#endif
}

void Map::on_buttonZoomIn_pressed()
{
#if defined(BROWSER)
    mapview->setTextSizeMultiplier( size += 0.1 );
#else
    zoomLevel += 3;

    if ( zoomLevel > 17 )
        zoomLevel = 17;

    zoom();
#endif
}

void Map::on_buttonZoomOut_pressed()
{
#if defined(BROWSER)
    mapview->setTextSizeMultiplier( size -= 0.1 );
#else
    zoomLevel -= 3;

    if ( zoomLevel < 0 )
        zoomLevel = 0;

    zoom();
#endif
}

void Map::finished(QNetworkReply *reply)
{
    qDebug("Finished");

    QString replyStr ( mapline->text());

    coordinateStrList = replyStr.split(",");

    foreach( QString string, coordinateStrList )
    {
        qDebug() << string;
    }

        QStringList scriptStr;
        scriptStr
             << "var myOptions = {scrollwheel:true,navigationControl:true,mapTypeControl:true,scaleControl:true,draggable:true};"
            << "var map = new google.maps.Map(document.getElementById(\"map\"),myOptions);"
//            << "var map = new GMap2(document.getElementById(\"map\"));"
            << "var bounds = new GLatLngBounds;"
            << "var markers = [];"
            << "map.setCenter( new GLatLng(0,0),2 );";

        scriptStr
            << QString("markers[%1] = new GMarker(new GLatLng(%2, %3));")
            .arg(0)
               .arg(coordinateStrList[0].toFloat())
               .arg(coordinateStrList[1].toFloat());

        scriptStr
            << "for( var i=0; i<markers.length; ++i ) {"
            << " bounds.extend(markers[i].getPoint());"
            << " map.addOverlay(markers[i]);"
            << "}"
            << "map.setCenter(bounds.getCenter());";
            //<< "map.doubleClickZoomEnabled();"
//        << "options = $.extend({scrollwheel:true,navigationControl:true,mapTypeControl: false,scaleControl: false,draggable:true,mapTypeId: google.maps.MapTypeId.ROADMAP},options);";

     zoomLevel = 3;
     mapview->page()->mainFrame()->evaluateJavaScript( scriptStr.join("\n") );


     longitude = coordinateStrList[0].left(5);
     latitude = coordinateStrList[1].left(5);
}

void Map::showProgressBar(bool visible)
{
#if !defined(BROWSER)
    QString cmd;
    if ( visible )
        cmd = "$(\"#anim\").css(\"left\",  \"25%\");";
    else
        cmd = "$(\"#anim\").css(\"left\",  \"-100%\");";

    qDebug() << cmd;

    mapview->page()->mainFrame()->evaluateJavaScript(cmd);
    mapview->update();
#else
    Q_UNUSED(visible);
    qDebug("ndef");
#endif
}

void Map::on_buttonSearch_pressed()
{
    if ( mapline->text().isEmpty() )
        return;

//    showProgressBar( true );

    QUrl request( "http://maps.google.com/maps/api/js?v=3.5&sensor=false");
//    QUrl request( "http://maps.google.com/maps/geo" );
//    request.addQueryItem( "q", mapline->text() );
//    request.addQueryItem( "sensor", false );
//    request.addQueryItem( "output", "csv" );
    manager->get( QNetworkRequest(request) );
    qDebug() << request;
}

void Map::zoom()
{
 QFile file( ":/gmaps_files/zoom.js");

// if ( !file.open(QIODevice::ReadOnly | QIODevice::Text) )
// {
//     QMessageBox::warning(this, "File error", "Opening failed!");
// }
// else
// {
     // Read and evaluate the javascript functions
     QString functions = file.readAll();
     QWebFrame* frame = mapview->page()->mainFrame();
     frame->evaluateJavaScript( functions );

     // Frame now knows what the js functions addCalculator()
     // and addDetachButton() are
     QString script = QString("zoom(%1, %2, %3);")
                      .arg( longitude)
                      .arg( latitude )
                      .arg( zoomLevel );

     frame->evaluateJavaScript(script);
//  }
}

void Map::populateJavaScriptWindowObject()
{
    mapview->page()->mainFrame()->evaluateJavaScript(jQuery);
}

void Map::on_webView_loadFinished(bool )
{
    qDebug("ndef");
    showProgressBar(false);
}
